package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @Classname CommentApiImpl
 * @Description TODO 点赞，评论，喜欢的实现类
 * @Date 2021/3/13 20:19
 * @Created by gan
 */
@Service
public class CommentApiImpl implements CommentApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    //点赞，保存
    @Override
    public Long save(Comment comment) {
       /* //添加comment
        comment.setId(new ObjectId());
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(comment);
        //更新数量
        updateCount(comment,1);
        //统计数量
        long count = getCount(comment);
        return count;*/

        //a.动态点赞记录保持 动态评论表
        comment.setId(ObjectId.get());
        comment.setCreated(System.currentTimeMillis());
        //点赞 //喜欢 //评论  需要接收消息的用户id
        if(comment.getPubType() == 1){
            Query query = new Query();
            Publish publish = mongoTemplate.findOne(query,Publish.class);
            comment.setPublishUserId(publish.getUserId());
        }
        mongoTemplate.save(comment);
        //b.根据发布id 更新发布表点赞数+1
        updateCount(comment,1);
        //c.根据发布id查询发布表点赞数
        Long count = getCount(comment);
        return count;
    }


    //删除点赞
    @Override
    public Long remove(Comment comment) {
        //删除comment
        Query removeQuery=new Query();
        //构建删除条件
        removeQuery.addCriteria(Criteria.where("publishId").is(comment.getPublishId())
                        .and("commentType").is(comment.getCommentType())
                        .and("userId").is(comment.getUserId()));
        mongoTemplate.remove(removeQuery,Comment.class);
        //计数减一
        updateCount(comment,-1);
        long count = getCount(comment);
        return count;
    }


    //分页查询
    @Override
    public PageResult<Comment> findPage(String publishId, int page, int pagesize) {
        //构建分页结果
        PageResult pageResult = new PageResult();
        pageResult.setPage((long)page);
        pageResult.setPagesize((long)pagesize);

        Query query = new Query();
        // 查询条件，属于某个动态，且评论类型为2 即评论信息
        query.addCriteria(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(2));
        // 统计总数
        long count = mongoTemplate.count(query, Comment.class);
        pageResult.setCounts(count);
        // 查询分页结果集，按创建时间降序
        query.with(PageRequest.of(page-1,pagesize)).with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        pageResult.setItems(comments);
        return pageResult;
    }


    //通过发布者id和评论的类型分页查询
    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Integer commentType, Long userId) {
        //创造分页结果
        PageResult<Comment> pageResult=new PageResult<>();
        //构建查询条件
        Query query=new Query();
        query.addCriteria(Criteria.where("publishUserId").is(userId)
        .and("commentType").is(commentType)).limit(pagesize).skip((page-1)*pagesize);
        //获取评论列表中的数据
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        long total = mongoTemplate.count(query, Comment.class);
        int pages = total / pagesize + total % pagesize > 0 ? 1 : 0;
        //构造分页结果
        pageResult.setCounts(total);
        pageResult.setPage((long)page);
        pageResult.setPagesize((long)pagesize);
        pageResult.setPages((long)pages);
        pageResult.setItems(comments);
        //返回
        return pageResult;
    }


    /**
     * 更新动态表中对应列的计数值
     * @param comment
     * @param value
     */
    private void updateCount(Comment comment,int value){
        Query updateQuery = new Query();
        updateQuery.addCriteria(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        update.inc(comment.getCol(),value);
        // 动态统计
        Class<?> cls = Publish.class;
        if(comment.getPubType() == 3){
            // 对动态中的评论的点赞数
            cls = Comment.class;
        }
        mongoTemplate.updateFirst(updateQuery,update,cls);
    }

    /**
     * 根据类型统计评论数量
     * @param comment
     * @return
     */
    private long getCount(Comment comment) {
        Query query = new Query(Criteria.where("id").is(comment.getPublishId()));
        if(comment.getPubType() == 1){
            Publish publish = mongoTemplate.findOne(query, Publish.class);
            if(comment.getCommentType() == 1){// //评论类型，1-点赞，2-评论，3-喜欢
                return (long)publish.getLikeCount();
            }
            if(comment.getCommentType() == 2){// //评论类型，1-点赞，2-评论，3-喜欢
                return (long)publish.getCommentCount();
            }
            if(comment.getCommentType() == 3){// //评论类型，1-点赞，2-评论，3-喜欢
                return (long)publish.getLoveCount();
            }
        }
        if(comment.getPubType() == 3){
            Comment cm = mongoTemplate.findOne(query, Comment.class);
            return (long)cm.getLikeCount();
        }
        return 99l;
    }
}
